package uit.nfcmenu.util;

import java.util.ArrayList;

import uit.nfcmenu.db.model.IDataChangeHandler;
import uit.nfcmenu.db.model.OrderModel;
import uit.nfcmenu.manager.DatabaseManager;
import uit.nfcmenu.manager.OrderManager;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;


public class GetOrdersAsyncTask extends AsyncTask<String, ArrayList<OrderModel>, Void> {
	public static final String tag = GetOrdersAsyncTask.class.getSimpleName();

	// ===========================================
	// Fields
	// ===========================================

	ArrayList<OrderModel> mOrders;
	IDataChangeHandler mMainDataScreen;
	Context mContext;

	boolean mIsRunning;

	static GetOrdersAsyncTask mInstance;

	// ===========================================
	// Constructors, System Methods, Event Methods
	// ===========================================
	private GetOrdersAsyncTask(IDataChangeHandler mainDataScreen) {
		mMainDataScreen = mainDataScreen;
		mContext = mainDataScreen.getContext();
		mIsRunning = false;
	}

	public static GetOrdersAsyncTask getInstance(IDataChangeHandler context) {
		if (mInstance == null || mInstance.getStatus() == AsyncTask.Status.FINISHED)
			mInstance = new GetOrdersAsyncTask(context);
		return mInstance;
	}

	@Override
	protected Void doInBackground(String... params) {
		Log.i(tag, "doInBackground()");
		
		mIsRunning = true;
		long nexttime = System.currentTimeMillis() + CommConstant.TIME_PAUSE_UPDATE_DATA;
		while (mIsRunning) {
			long current = System.currentTimeMillis();
			if (current >= nexttime) {
				nexttime = current + CommConstant.TIME_PAUSE_UPDATE_DATA;

				Log.i(tag, "be in loop... check data");
				if (NetworkHelper.checkNetworkStatus(mContext)) {
					// commit all requests in stock
					pushRequest();
					try {
						mOrders = WSMapping.getAllOrderFromServer(mContext);
					} catch (MyException e1) {
						e1.printStackTrace();
					}
					// handle data // insert data to db
					if (mOrders != null && mOrders.size() != 0) {
						try {
							OrderManager.getInstance(mContext).updateOrders();
						} catch (MyException e) {
							e.printStackTrace();
						}
						// notify data changed 
						DatabaseManager.getInstance(mMainDataScreen).notifyDataChanged();
					} else {
						Log.e(tag, "Get data fail");
					}
				}
			}

			try {
				Thread.sleep(CommConstant.TIME_PAUSE_UPDATE_VIEW); // pause
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Log.i(tag, "end of doInBackground");
		mIsRunning = false;
		return null;
	}
	
	private void pushRequest(){ // FIXME 
		while (CommConstant.savedRequests.size() > 0) {
			String url = CommConstant.savedRequests.remove(0);
			//String response = WebserviceHelper.callWS(url);
		}
	}

	

	/*
	 * TODO Just for test
	 */
//	private ArrayList<MenuModel> getMenuInTest(Context context) {
//		ArrayList<MenuModel> menus = new ArrayList<MenuModel>();
//		// get date from web-service
//		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
//				"response/menu.json"); // get from assets
//		// parse data
//		menus = JSONParser.parseMenus(response);
//		return menus;
//	}
//
//	private ArrayList<ItemModel> getItemInTest(Context context) {
//		ArrayList<ItemModel> items = new ArrayList<ItemModel>();
//		// get date from web-service
//		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
//				"response/item.json"); // get from assets
//		// parse data
//		items = JSONParser.parseItems(response);
//		return items;
//	}
//
//	private ArrayList<OrderModel> getOrderInTest(Context context) {
//		ArrayList<OrderModel> orders = new ArrayList<OrderModel>();
//		// get date from web-service
//		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
//				"response/order.json"); // get from assets
//		// parse data
//		orders = JSONParser.parseOrders(response); 
//		return orders;
//	}

	/*
	 * Other
	 */
	// @Override
	// protected void onProgressUpdate(ArrayList<OrderModel>... values) {
	// if (values != null) {
	// mDBManager.insertOrderStates(values[0]);
	// // check item
	// }
	// else {
	// Log.w(tag, "there are errors in  getting data");
	// }
	// super.onProgressUpdate(values);
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	// super.onPostExecute(result);
	// }

	// ===========================================
	// Action Methods
	// ===========================================

	public boolean stop() {
		Log.i(tag, "stop()");
		if (mIsRunning) {
			mIsRunning = false;
		}
		return mIsRunning;
	}

	public boolean isRunning() {
		return mIsRunning;
	}
}
